package cn.holy.app.xcddt.ui.activity.record

import android.app.Activity
import android.app.SearchableInfo
import android.content.Context
import android.content.Intent
import android.database.DataSetObserver
import android.os.Bundle
import android.os.PersistableBundle
import androidx.core.content.ContextCompat
import androidx.appcompat.widget.SearchView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import cn.holy.app.xcddt.R
import cn.holy.app.xcddt.ui.activity.base.BaseActivity
import com.alibaba.android.arouter.facade.annotation.Route
import kotlinx.android.synthetic.main.activity_map.*

import com.amap.api.maps.AMap
import com.amap.api.maps.model.MyLocationStyle
import com.amap.api.services.poisearch.PoiSearch
import com.amap.api.maps.model.LatLng
import com.amap.api.maps.model.CameraPosition
import com.amap.api.maps.CameraUpdateFactory
import com.amap.api.maps.CameraUpdate
import com.amap.api.maps.model.MarkerOptions
import com.amap.api.services.core.LatLonPoint
import com.amap.api.services.geocoder.*
import com.qmuiteam.qmui.util.QMUIStatusBarHelper
import com.orhanobut.logger.Logger
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.amap.api.services.help.InputtipsQuery
import com.amap.api.services.help.Inputtips
import com.amap.api.services.help.Tip
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.widget.popup.QMUIListPopup
import com.qmuiteam.qmui.widget.popup.QMUIPopup
import com.zhy.adapter.recyclerview.CommonAdapter
import com.zhy.adapter.recyclerview.base.ViewHolder


/**
 * Created by xionghao-mbp on 2018/3/26.
 */
@Route(path = "/app/map")
class MapActivity : BaseActivity(), AMap.OnCameraChangeListener, GeocodeSearch.OnGeocodeSearchListener {
    override fun onGeocodeSearched(result: GeocodeResult?, p1: Int) {
        result?.let {
            Logger.d(it.geocodeAddressList)
            val first = it.geocodeAddressList.first()
            needUpdate = false
            address = first.formatAddress
            changePosition(first.latLonPoint.latitude, first.latLonPoint.longitude)
        }
    }

    override fun onRegeocodeSearched(p0: RegeocodeResult?, p1: Int) {
        Logger.d(p0?.regeocodeAddress?.formatAddress)
        p0?.regeocodeAddress?.let {
            address = it.formatAddress
        }

    }

    private var needUpdate: Boolean = true

    override fun onCameraChangeFinish(p0: CameraPosition?) {
        if (needUpdate) {
            val point = LatLonPoint(p0?.target!!.latitude, p0.target.longitude)
            val query = RegeocodeQuery(point, 200f, GeocodeSearch.AMAP)
            geocoderSearch.getFromLocationAsyn(query)
        }
        needUpdate = true
    }

    override fun onCameraChange(p0: CameraPosition?) {

    }

    private lateinit var aMap: AMap
    private var address: String = ""
    private var snippet: MarkerOptions? = null
    private var searchOptions: ArrayList<Tip> = ArrayList()

    override fun initData() {

        val latitude = intent.getDoubleExtra("latitude", 0.0)
        val longitude = intent.getDoubleExtra("longitude", 0.0)
        changePosition(latitude, longitude)


    }

    private fun changePosition(latitude: Double, longitude: Double) {
        val mCameraUpdate = CameraUpdateFactory.newCameraPosition(CameraPosition(LatLng(latitude, longitude), 14f, 30f, 0f))
        aMap.animateCamera(mCameraUpdate, 1500, object : AMap.CancelableCallback {
            override fun onFinish() {

            }

            override fun onCancel() {
            }

        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        aMapView.onCreate(savedInstanceState)
    }

    override fun onDestroy() {
        super.onDestroy()
        aMapView.onDestroy()
    }

    override fun onResume() {
        super.onResume()
        aMapView.onResume()
    }

    override fun onPause() {
        super.onPause()
        aMapView.onPause()
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        aMapView.onSaveInstanceState(outState)
    }

    private lateinit var geocoderSearch: GeocodeSearch

    private lateinit var adapter: AutoCompleteAdapter

    override fun initView() {
        QMUIStatusBarHelper.translucent(this)
        QMUIStatusBarHelper.setStatusBarDarkMode(this)
        top_bar.setTitle("开始新巡查").setTextColor(ContextCompat.getColor(this, R.color.colorWhite))
        top_bar.addLeftImageButton(R.mipmap.ic_back, R.id.action_close).setOnClickListener({ finish() })
        top_bar.addRightTextButton("选择", R.id.action_save).setOnClickListener {

            if (address != "") {
                val intent = Intent()
                val target = aMap.cameraPosition.target
                intent.putExtra("latitude", target.latitude)
                intent.putExtra("longitude", target.longitude)
                intent.putExtra("address", address)
                setResult(Activity.RESULT_OK, intent)
                finish()
            } else {
                showTips("正在获取地址", QMUITipDialog.Builder.ICON_TYPE_INFO)
            }

        }
        search_bar.isIconified = true
//        search_bar.showDividers = true
        adapter = AutoCompleteAdapter(searchOptions, this)
        val qmuiListPopup = QMUIListPopup(this, QMUIPopup.DIRECTION_BOTTOM, adapter)
        qmuiListPopup.create(QMUIDisplayHelper.getScreenWidth(this) - QMUIDisplayHelper.dp2px(this, 32),
                QMUIDisplayHelper.dp2px(this, 200), object : AdapterView.OnItemClickListener {
            override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                var tip = searchOptions[position]
                needUpdate = false
                address = tip.name
                changePosition(tip.point.latitude, tip.point.longitude)
                search_bar.setQuery(tip.name,false)
                qmuiListPopup.dismiss()
            }

        })

        search_bar.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                address = query!!
                searchLocation(query)
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                val inputquery = InputtipsQuery(newText, "重庆")
                inputquery.cityLimit = true
                val inputTips = Inputtips(this@MapActivity, inputquery)
                inputTips.setInputtipsListener { mutableList, i ->
                    Logger.d(mutableList)
                    searchOptions.clear()
                    searchOptions.addAll(mutableList)
                    adapter.notifyDataSetChanged()
                    qmuiListPopup.show(search_bar)
                }
                inputTips.requestInputtipsAsyn()
                return true
            }
        })

        aMap = aMapView.map
        val myLocationStyle = MyLocationStyle()//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000) //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_FOLLOW_NO_CENTER);
        myLocationStyle.showMyLocation(false)

        aMap.myLocationStyle = myLocationStyle//设置定位蓝点的Style
        aMap.uiSettings.isMyLocationButtonEnabled = true
        aMap.isMyLocationEnabled = true// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。
        geocoderSearch = GeocodeSearch(this)

        aMap.setOnCameraChangeListener(this)
        geocoderSearch.setOnGeocodeSearchListener(this)

//        aMap.setmap
    }

    private fun searchLocation(query: String?) {
        geocoderSearch.getFromLocationNameAsyn(GeocodeQuery(query, "重庆"))

    }

    override fun initLayout() {
        setContentView(R.layout.activity_map)
    }

    class AutoCompleteAdapter constructor(private val datas: ArrayList<Tip>, var context: Context) : BaseAdapter() {


        override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
            var holder: ViewHolder? = null
            var view = convertView
            if (convertView != null) {
                holder = view?.tag as ViewHolder?
            } else {
                view = LayoutInflater.from(context).inflate(R.layout.search_autocomplete_item, parent, false)
                holder = ViewHolder()
                holder.text = view.findViewById(R.id.tv_title) as? TextView
                view.tag = holder
            }

            holder?.text?.text = datas[position].name

            return view!!
        }

        override fun getItem(position: Int): Any {
            return datas[position]
        }

        override fun getItemId(position: Int): Long {
            return 0
        }

        override fun getCount(): Int {
            return datas.size
        }

        class ViewHolder {
            public var text: TextView? = null
        }
    }

}